package com.example.mybatis.rest;

import com.example.mybatis.dao.OutputDao;
import com.example.mybatis.moudle.Paykind;
import com.example.mybatis.dao.PaykindDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 阿恩
 * @date 2020/11/2016:41
 */
@RestController
@RequestMapping("/kind")
public class PayKindRest {
    @Autowired
    SqlSessionFactory factory;

    /**
     * 输出所有种类
     * 2支出,1收入
     * http://localhost:9090/kind/findAll/2
     * @return
     */
    @GetMapping("findAll/{flag}")
    public List<Paykind> findAll(@PathVariable("flag") int flag){
        SqlSession sess=factory.openSession();
        PaykindDao paykindDao=sess.getMapper(PaykindDao.class);
        List<Paykind> list=paykindDao.outputAll(flag);
        sess.close();
        return list;
    }

    /**
     * 新增一条记录
     * http://localhost:9090/kind/insert/2/电费
     * @param flag 1收入2支出
     * @param name 名称
     */
    @GetMapping("insert/{flag}/{name}")
    public void insert (@PathVariable("flag")int flag,@PathVariable("name")String name){
        Paykind paykind=new Paykind(1,name,flag);
        SqlSession sess=factory.openSession();
        PaykindDao paykindDao=sess.getMapper(PaykindDao.class);
        paykindDao.insertSelective(paykind);
        sess.commit();
        sess.close();
    }

    /**
     * 根据主键删除一条记录
     * http://localhost:9090/kind/delete/1
     * @param id
     */
    @GetMapping("delete/{id}")
    public void deleteByPrimaryKey(@PathVariable("id") int id){
        SqlSession sess=factory.openSession();
        PaykindDao paykindDao=sess.getMapper(PaykindDao.class);
        paykindDao.deleteByPrimaryKey(id);
        sess.commit();
        sess.close();
    }

    /**
     * 更新一条记录
     * http://localhost:9090/kind/update
     * @param paykind
     * @return
     */
    @PostMapping("update")
    @ResponseBody
    public Paykind update(@RequestBody Paykind paykind){
        try {
            System.out.println(paykind);
            SqlSession sess=factory.openSession();
            PaykindDao paykindDao=sess.getMapper(PaykindDao.class);
            paykindDao.updateByPrimaryKeySelective(paykind);
            sess.commit();
            sess.close();
            return paykind;
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        finally {
            return null;
        }
    }
}
